package edgeEntity

import (
	"encoding/json"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"strconv"
)

type PeriodRecordEntity struct {
	BaseEntity *commEntity.BaseEntity // 基本信息

	TaskId      int64
	RecordBatch string
	DeviceId    int64

	ObjectName  string                 // 事件名称
	ObjectValue map[string]interface{} // 配置参数
}

type periodRecordPo struct {
	Id         int64 `json:"id" db:"id"`                  // 对象id
	CreateTime int64 `json:"createTime" db:"create_time"` // 创建时间
	UpdateTime int64 `json:"updateTime" db:"update_time"` // 更新时间

	TaskId      int64  `json:"taskId" db:"task_id"`           // 对象id
	RecordBatch string `json:"recordBatch" db:"record_batch"` // 设备厂商名称
	DeviceId    int64  `json:"deviceId" db:"device_id"`       // 对象id

	ObjectName  string                 `json:"objectName" db:"object_name"`   // 事件名称
	ObjectValue map[string]interface{} `json:"objectValue" db:"object_value"` // 扩展参数
}

func (e *PeriodRecordEntity) Type() string {
	return "PeriodRecordEntity"
}

func (e *PeriodRecordEntity) TableName() string {
	return "tb_period_record"
}

func (e *PeriodRecordEntity) GetBaseEntity() *commEntity.BaseEntity {
	return e.BaseEntity
}

func (e *PeriodRecordEntity) Instance() *PeriodRecordEntity {
	return &PeriodRecordEntity{
		BaseEntity:  new(commEntity.BaseEntity),
		ObjectValue: make(map[string]interface{}),
	}
}

func (e *PeriodRecordEntity) NewEntity() commEntity.IEntity {
	return e.Instance()
}

func (e *PeriodRecordEntity) NewPo() interface{} {
	return &periodRecordPo{
		ObjectValue: make(map[string]interface{}),
	}
}

func (e *PeriodRecordEntity) MakeServiceKey() string {
	p := e.MakeServiceKeyList()
	return commEntity.MakeServiceKey(p)
}

func (e *PeriodRecordEntity) MakeServiceKeyList() []string {
	var p []string
	p = append(p, strconv.FormatInt(e.BaseEntity.Id, 10))
	return p
}

func (e *PeriodRecordEntity) BuildByJson(jsn *string) error {
	var po periodRecordPo
	err := json.Unmarshal([]byte(*jsn), &po)
	if err != nil {
		return err
	}

	e.BuildByPo(&po)
	return nil
}

func (e *PeriodRecordEntity) BuildToJson() (string, error) {
	po := e.BuildToPo()
	code, err := json.Marshal(po)
	if err != nil {
		return "", err
	}

	return string(code), nil
}

func (e *PeriodRecordEntity) BuildByPo(pop interface{}) {
	ptr := e
	po := pop.(*periodRecordPo)

	ptr.BaseEntity.Id = po.Id
	ptr.BaseEntity.CreateTime = po.CreateTime
	ptr.BaseEntity.UpdateTime = po.UpdateTime

	ptr.TaskId = po.TaskId
	ptr.RecordBatch = po.RecordBatch
	ptr.DeviceId = po.DeviceId

	ptr.ObjectName = po.ObjectName
	ptr.ObjectValue = po.ObjectValue
}

func (e *PeriodRecordEntity) BuildToPo() interface{} {
	ptr := e
	po := periodRecordPo{}

	po.Id = ptr.BaseEntity.Id
	po.CreateTime = ptr.BaseEntity.CreateTime
	po.UpdateTime = ptr.BaseEntity.UpdateTime

	po.TaskId = ptr.TaskId
	po.RecordBatch = ptr.RecordBatch
	po.DeviceId = ptr.DeviceId

	po.ObjectName = ptr.ObjectName
	po.ObjectValue = ptr.ObjectValue

	return &po
}
